import { HubConnectionBuilder, HubConnectionState } from "@microsoft/signalr";
import { useUserStore } from "@/store";
import { getAccessToken } from "./cacheUtils";
import { CacheKeyEnum } from "@/enums/CacheKeyEnum";
import { ChatMessage } from "@/api/chat/message/model";

const store = useUserStore();
const connection = new HubConnectionBuilder()
  .withUrl(import.meta.env.VITE_APP_BASE_SOCKET, {
    accessTokenFactory: () => {
      return getAccessToken().replace(CacheKeyEnum.TOKEN_TYPE_KEY + " ", "");
    },
  })
  .withAutomaticReconnect()
  .build();

export const startConnection = () => {
  if (connection.state === HubConnectionState.Disconnected) {
    connection.start().then(() => {
      console.log("signalr started");
      store.isOnline = true;
    });
  }
};

export const stopConnection = () => {
  connection.stop().then(() => {
    console.log("signalr stopped");
    store.isOnline = false;
  });
};

/**
 * 发生即时消息
 * @param methodName
 * @param userid
 * @param message
 */
export const sendSignalR = (methodName: string = "OnMessage", message: ChatMessage) => {
  if (connection.state === HubConnectionState.Disconnected) {
    connection.start().then(() => {
      sendSignalR(methodName, message);
    });
  } else {
    const json = JSON.stringify(message);
    connection.send(methodName, json).then(() => {
      console.log("signalr sended");
    });
  }
};

/**
 * 接收即时消息
 * @param methodName
 * @param receviceMethod
 */
export const receiveSignalR = (
  methodName: string = "OnMessage",
  receviceMethod: (msg: ChatMessage) => void
) => {
  connection.on(methodName, (message: ChatMessage) => {
    receviceMethod(message);
  });
};
